package cn.fancy.sdk.crash;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import cn.fancy.sdk.login.utils.MobileSignHelper;
import cn.fancy.sdk.utils.CommMessage;

import android.content.Context;
import android.util.Log;


public class QCCrashLogPrint  {  
	
	private static QCCrashLogPrint instance  = null;
	
	private  String crashFile = "";
	
	private FileOutputStream crashOstream = null;
	
	private String TAG = "QCCrashLogPrint";
	
	private String logfile = "qc_crash.log";
	
	public static QCCrashLogPrint getInstance(){
		
		if( instance == null ){
			instance = new QCCrashLogPrint();
		}
		
		return instance;
	}
	
	private QCCrashLogPrint(){
		
	}
	
	
	public void initPrint(Context context){
		String logdir = CommMessage.GetSdcardRootPath(context);
		
		if( logdir == null || logdir.equals("")){
			Log.e(TAG,"GetSdcardRootPath return null or nil");
			return;
		}
		
		crashFile = logdir + "fancy/" + logfile;
		createStream(crashFile);
	}
	

	
	private void createStream(String filepath)
	{
		if ( crashOstream != null )
			return ;
		
		try
		{
			File file = new File( filepath );
			if ( file.exists() == false )
			{
				// 创建目录
				new File( file.getParent() ).mkdirs();
			}else{
				//如果存在该文件，先删除该文件
				file.delete();
				file.createNewFile();
			}
			
			crashOstream = new FileOutputStream( file );
			String strChangeLine = "\n\n\n";
			crashOstream.write( strChangeLine.getBytes() );
			String strBegin = "---------------------------------------------------------------------------\n";
			crashOstream.write( strBegin.getBytes() );
			crashOstream.flush();
		}
		catch ( Exception e )
		{
			e.printStackTrace();
		}
	}
	
	
	public void printCrash(String crashinfo){
		if( crashOstream == null || crashFile == null || crashFile.equals("")){
			Log.e(TAG,"crashFile is nil");
			return;
		}
		
		String finalinfo = "\nQCCrash===========infobegin\n\n" + "[crashinfo] " + crashinfo + "\n"  + "QCCrash===========infoend\n\n";
		try
		{
			crashOstream.write( finalinfo.getBytes() );
			crashOstream.flush();
			Log.e(TAG,finalinfo);
			MobileSignHelper.updateKeyValue("iscrash","1");
			
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}
	
	//打印关键日志
	public void printCrux(String log){
		if( crashOstream == null || crashFile == null || crashFile.equals("")){
			Log.e(TAG,"crashFile is nil");
			return;
		}
		
		String info = "\nPACE=====================begin" + log + "PACE=====================end\n";
		try
		{
			crashOstream.write( info.getBytes() );
			crashOstream.flush();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}
	

}  


